<template>
  <div class="about-master-container">
    <base-breadcrumb>
      <b-steps
        :current="stepVal"
        direction="vertical"
        @change.self="stepChange"
      >
        <b-step title="基本信息">
          <a-card
            v-show="activeKey[0]"
            slot="description"
            v-loading="loading"
            :bordered="false"
          >
            <a-form-model
              ref="ruleForm"
              :model="formData"
              :rules="rules"
            >
              <a-row>
                <a-col span="8">
                  <a-form-model-item label="资产编号">
                    <BaseInput
                      v-model="formData.assetsNum"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="资产类别">
                    <a-select
                      v-model="formData.assetsTypeId"
                      :disabled="state === 3"
                      @change="categoryChange"
                    >
                      <a-select-option
                        v-for="item in categoryArr"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item
                    v-show="categoryCode === '250002'"
                    label="项目资产分类"
                  >
                    <a-select
                      v-model="formData.projectAssetsTypeId"
                      :disabled="state === 3"
                    >
                      <a-select-option
                        v-for="item in categoryArr2"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                  <a-form-model-item
                    v-show="categoryCode === '250003'"
                    label="租赁期限"
                  >
                    <a-range-picker
                      v-model="formData.leaseDate"
                      :disabled="state === 3"
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="保管人"
                    prop="custodianStr"
                  >
                    <a-input-search
                      v-model="formData.custodianStr"
                      placeholder="请选择"
                      :disabled="state === 3"
                      @search="openPerson"
                      @click="openPerson"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="保管部门">
                    <a-select
                      v-model="formData.custodianOrgId"
                      :disabled="state === 3"
                    >
                      <a-select-option
                        v-for="item in orgs"
                        :key="item.id"
                        :value="item.id"
                      >
                        {{ item.pName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="电话">
                    <BaseInput
                      v-model="formData.custodianTel"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
              <a-row>
                <a-col span="8">
                  <a-form-model-item
                    label="资产所属单位"
                    prop="orgStr"
                  >
                    <a-input
                      v-model="formData.orgStr"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建人">
                    <BaseInput
                      v-model="formData.creatorName"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
                <a-col span="8">
                  <a-form-model-item label="创建时间">
                    <BaseInput
                      v-model="formData.createTime"
                      disabled
                    />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
            <div class="pub-next-btn">
              <a-button
                v-show="state !== 3"
                type="primary"
                @click="temporaryStorage()"
              >
                保存草稿
              </a-button>
              <a-button
                type="primary"
                @click="temporaryStorage(true)"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="资产信息">
          <a-card
            v-if="activeKey[1]"
            slot="description"
            :bordered="false"
          >
            <info
              ref="info"
              :state="state"
              :row="formData ? formData : null"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                :disabled="state === 3"
                @click="saveInfo"
              >
                保存
              </a-button>
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <b-step title="维修记录">
          <a-card
            v-if="activeKey[2]"
            slot="description"
            :bordered="false"
          >
            <maintain
              :id="formData ? formData.id : null"
              ref="maintain"
              :state="state"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
              <a-button
                type="primary"
                @click="next"
              >
                下一步
              </a-button>
            </div>
          </a-card>
        </b-step>
        <!--                <b-step title="进出场记录">-->
        <!--                    <a-card :bordered="false" slot="description" v-if="activeKey[3]">-->
        <!--                        <into-play :state="state" :id="formData ? formData.id : null" ref="maintain"></into-play>-->
        <!--                        <div class="pub-next-btn">-->
        <!--                            <a-button type="primary" @click="previous">上一步</a-button>-->
        <!--                            <a-button type="primary" @click="next">下一步</a-button>-->
        <!--                        </div>-->
        <!--                    </a-card>-->
        <!--                </b-step>-->
        <b-step title="相关附件">
          <a-card
            v-if="activeKey[3]"
            slot="description"
            :bordered="false"
          >
            <u-table
              :upload-list="addFile"
              :delete-url="fileDel"
              :is-show="state !== 3"
              :list-url="fileList"
              :business-id="formData.id"
              business-code="MM01"
            />
            <div class="pub-next-btn">
              <a-button
                type="primary"
                @click="previous"
              >
                上一步
              </a-button>
            </div>
          </a-card>
        </b-step>
      </b-steps>
      <div class="pub-header-btn page-btn-right-top">
        <template v-if="state !== 3">
          <a-button
            type="primary"
            :loading="loading"
            @click="submit"
          >
            提交
          </a-button>
          <a-button
            type="primary"
            :loading="loading"
            @click="temporaryStorage"
          >
            保存
          </a-button>
        </template>
        <a-button @click="handleClose">
          关闭
        </a-button>
      </div>
    </base-breadcrumb>
    <person-list
      ref="personList"
      :other-data="{rootOrgId:formData.orgId}"
      :org-id="formData.branchComId"
      @getPerson="getPerson"
    />
  </div>
</template>

<script>
import maintain from '../components/maintain/maintain'
import info from '../components/info/info'
import { selectOption } from '@/api/material/goods/goods'
import {
    parameterAdd,
    parameterEdit,
    audit,
    addFile,
    fileList,
    fileDel,
    organizations,
    employeesDetail,
    findListByMainId
} from '@/api/material/assets/parameter'

export default {
	name:'a'+Date.now(),
    components: {
        maintain,
        info
    },
    data() {
        return {
            activeKey: [true, false, false, false, false, false, false],
            loading: false,
            state: Number(this.$route.query.state),
            isSubmit: false,
            formData: {
                orgStr: '',
                custodianStr: '',
                custodianTel: '',
                createTime: this.getNowTime(),
                creatorName: JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
            },
            orgs: [],
            isNext: false,
            stepVal: 0,
            addFile: addFile(),
            fileDel: fileDel(),
            fileList: fileList(),
            rules: {
                custodianStr: { required: true, message: '保管人不能为空', trigger: 'change' },
                orgStr: { required: true, message: '资产所属单位不能为空', trigger: 'change' }
            },
            categoryArr: [],
            categoryArr2: [],
            categoryCode: null
        }
    },
    watch: {
        stepVal(newVal, oldVal) {
            this.$set(this.activeKey, newVal, true)
        }
    },
    mounted: async function() {
        this.loading = true
        await this.getOption()
        await this.getOption2()
        if (this.$route.query.id && this.state !== 1) {
            this.formData.id = this.$route.query.id
            this.isSubmit = true
            await this.getDetails()
            await this.getOrgs()
        } else {
          this.formData.orgStr = this.$currentPost().name
          this.formData.orgId = this.$currentSubCompany().companyId
        }
        this.loading = false
    },
    methods: {
        async getDetails() {
            this.loading = true
            let res = await findListByMainId({ id: this.formData.id })
          if (res.code === 200) {
                this.formData = this.$assign(this.formData, res.data)

                let category = this.categoryArr.find(v => v.id == this.formData.assetsTypeId)
                if (category){
                    this.categoryCode = category.code
                }
            }
            this.loading = false
        },

        handleClose() {
            this.$close()
        },
        saveInfo: function() {
            this.$refs.info.temporaryStorage()
        },
        async getPerson(row) {
            this.formData.custodianStr = row.name
            this.formData.custodianTel = row.phoneNum
            this.formData.custodianId = row.id
            // this.formData.custodianId = row.userId

            this.formData.custodianOrgId = ''
            let resData = await employeesDetail({ id: row.id });
            console.log('custodianId',resData)
            this.orgs = []
            let posts = resData?.data.posts
            console.log('postspostsposts',posts)
            if (posts && posts.length) {
                let orgIds = posts.map(v => v.orgId)
                console.log('orgIdorgIdorgIdorgId',orgIds)
                let res = await organizations({ pageSize: orgIds.length, pageNum: 1, ids: orgIds.join(',') })
                // this.$console(res.data)
                this.orgs = res.data.list
                if (this.orgs.length) {
                    this.formData.custodianOrgId = this.orgs[0].id
                }
            }
            // this.$console(this.orgs)
        },

        async getOrgs() {
            if (this.formData.custodianId) {
                let res = await employeesDetail({ id: this.formData.custodianId })
                // let res = await getOrgEmployeeByUser(this.formData.custodianId)
                // let res = await employeesDetail({ id: 11 })
                let posts = res.data.posts
                if (posts) {
                    let orgIds = posts.map(v => v.orgId)
                    let res = await organizations({ pageSize: orgIds.length, pageNum: 1, ids: orgIds.join(',') })
                    // this.$console(res.data)
                    this.orgs = res.data.list
                }
            }
            // this.$console(this.orgs)

        },

        openPerson: function() {
            this.$refs.personList.open()
        },
        categoryChange(val) {
            this.categoryArr.map((item) => {
                if (item.id === val) {
                    this.categoryCode = item.code
                }
            })
        },
        stepChange: function(val) {
            if (!this.formData.id) {
                if (val) {
                    this.$message.warning('切换步骤前请先填写基本信息')
                    this.stepVal = 0
                }
            } else {
                if (!this.isNext) {
                    this.$set(this.activeKey, val, !this.activeKey[val])
                }
            }
            this.isNext = false
        },
        next: function(val) {
            this.isNext = true
            this.stepVal++
        },
        previous: function() {
            this.isNext = true
            this.stepVal--
            if (this.stepVal < 0) {
                this.stepVal = 0
            }
        },
        async getOption() {
            let res = await selectOption({ type: 25 })
            if (res.code === 200) {
                this.categoryArr = res.data
                // this.formData.assetsTypeId = this.categoryArr[0].id
            }
        },
        getOption2: function() {
            let _this = this
            selectOption({
                type: 28
            }).then(res => {
                if (res.code === 200) {
                    _this.categoryArr2 = res.data
                    // _this.formData.assetsTypeId = _this.categoryArr[0].id
                }
            })
        },

        async submit() {
            // this.save('approve');
            if (this.isSubmit) {
                this.$submitConfirm(async () => {
                    this.loading = true
                    let res = await audit({ id: this.formData.id })
                    this.loading = false
                    if (res.code === this.SUCCESS_CODE) {
                        this.$message.success('提交成功')
                        this.loading = false
                        this.$router.push({ path: '/material/assets/parameter' })
                    }
                })
            } else {
                this.$message.warning('提交之前请先暂存')
            }
        },
        temporaryStorage(isNext) {
            if (this.state === 3) {
                this.next()
                return
            }
            this.$refs.ruleForm.validate((valid, object) => {
                if (valid) {
                    this.loading = true
                    if (this.state === 2 || this.formData.id) {
                        parameterEdit(this.formData).then(res => {
                            if (res.code === 200) {
                                this.$message.success('暂存成功')
                                this.isSubmit = true
                                if (isNext) {
                                    this.next()
                                }
                            }
                            this.loading = false
                        })
                    } else {
                        parameterAdd(this.formData).then(res => {
                            if (res.code === 200) {
                                this.formData.id = res.data.id
                                this.$message.success('暂存成功')
                                this.isSubmit = true
                                this.getDetails()
                                if (isNext) {
                                    this.next()
                                }
                            }
                            this.loading = false
                        })
                    }
                } else {
                    return false
                }
            })
        }
    }
}
</script>
